<template>
  <div class="video-debug-container">
    <!-- 调试信息 -->
    <div class="debug-panel" v-if="debug">
      <h4>调试信息</h4>
      <p><strong>原始src:</strong> {{ src }}</p>
      <p><strong>处理后src:</strong> {{ processedSrc }}</p>
      <p><strong>视频类型:</strong> {{ sourceType }}</p>
      <p><strong>是否为RTSP:</strong> {{ isRTSP }}</p>
      <p><strong>转码状态:</strong> {{ isConverted ? '已完成' : '转码中' }}</p>
      <p><strong>播放器状态:</strong> {{ playerStatus }}</p>
      <p><strong>错误信息:</strong> {{ errorMessage || '无' }}</p>
    </div>

    <!-- 视频播放器 -->
    <div class="video-wrapper">
      <video
        ref="videoPlayer"
        class="video-js vjs-default-skin"
        controls
        preload="auto"
        :width="width"
        :height="height"
        data-setup="{}"
        @loadeddata="onVideoLoaded"
        @error="onVideoError"
        @loadstart="onLoadStart"
        @stalled="onStalled"
        @waiting="onWaiting"
      >
        <source :src="processedSrc" :type="sourceType" />
        <p class="vjs-no-js">
          您的浏览器不支持HTML5视频播放。请
          <a href="https://videojs.com/html5-video-support/" target="_blank">
            升级浏览器
          </a>
        </p>
      </video>
      
      <!-- 备用视频标签 -->
      <video
        v-if="fallbackMode"
        ref="fallbackVideo"
        :src="processedSrc"
        controls
        :width="width"
        :height="height"
        style="position: absolute; top: 0; left: 0;"
      />
    </div>

    <!-- 状态提示 -->
    <div class="status-overlay" v-if="showStatus">
      <div class="status-content">
        <div v-if="isRTSP && !isConverted" class="loading-status">
          <div class="loading-spinner"></div>
          <p>正在转换RTSP流...</p>
          <p class="small-text">请确保后端转码服务已启动</p>
        </div>
        
        <div v-if="errorMessage" class="error-status">
          <span class="error-icon">❌</span>
          <p>{{ errorMessage }}</p>
          <button @click="retry" class="retry-btn">重试</button>
        </div>
        
        <div v-if="!hasVideoData" class="no-video-status">
          <span class="info-icon">📹</span>
          <p>等待视频加载...</p>
        </div>
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="controls" v-if="debug">
      <button @click="toggleDebug">{{ debug ? '关闭' : '开启' }}调试</button>
      <button @click="retry">重试加载</button>
      <button @click="testVideo">测试视频</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import videojs from 'video.js'
import 'video.js/dist/video-js.css'

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  width: {
    type: [String, Number],
    default: 640
  },
  height: {
    type: [String, Number],
    default: 360
  },
  autoplay: {
    type: Boolean,
    default: false
  },
  muted: {
    type: Boolean,
    default: false
  },
  loop: {
    type: Boolean,
    default: false
  },
  debug: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['ready', 'error', 'rtsp-convert', 'loaded', 'debug'])

// 引用和状态
const videoPlayer = ref(null)
const fallbackVideo = ref(null)
const player = ref(null)
const isConverted = ref(false)
const errorMessage = ref('')
const playerStatus = ref('初始化')
const hasVideoData = ref(false)
const fallbackMode = ref(false)
const showStatus = ref(true)

// 计算属性
const isRTSP = computed(() => {
  return props.src && props.src.startsWith('rtsp://')
})

const processedSrc = computed(() => {
  if (isRTSP.value) {
    return convertRTSPToHLS(props.src)
  }
  return props.src
})

const sourceType = computed(() => {
  const src = processedSrc.value
  if (!src) return 'video/mp4'
  
  if (src.includes('.m3u8')) return 'application/x-mpegURL'
  if (src.includes('.mp4')) return 'video/mp4'
  if (src.includes('.webm')) return 'video/webm'
  if (src.includes('.ogg')) return 'video/ogg'
  return 'video/mp4'
})

// 转换函数
const convertRTSPToHLS = (rtspUrl) => {
  console.log('🔍 RTSP转换:', rtspUrl)
  
  // 模拟转码延迟
  setTimeout(() => {
    isConverted.value = true
    const hlsUrl = rtspUrl
      .replace('rtsp://', 'http://')
      .replace(/:554\//, ':8080/hls/')
      .replace(/openUrl\//, '') + '.m3u8'
    
    console.log('🔄 转换完成:', { rtsp: rtspUrl, hls: hlsUrl })
    emit('rtsp-convert', { rtsp: rtspUrl, hls: hlsUrl })
  }, 2000)
  
  return rtspUrl
    .replace('rtsp://', 'http://')
    .replace(/:554\//, ':8080/hls/')
    .replace(/openUrl\//, '') + '.m3u8'
}

// 初始化播放器
const initPlayer = async () => {
  if (!videoPlayer.value) {
    console.error('❌ 视频元素未找到')
    return
  }

  try {
    playerStatus.value = '正在初始化播放器...'
    
    // 检查浏览器支持
    if (!videojs.getTech('html5').isSupported()) {
      throw new Error('浏览器不支持HTML5视频')
    }

    const options = {
      autoplay: props.autoplay,
      controls: true,
      responsive: true,
      fluid: true,
      muted: props.muted,
      loop: props.loop,
      sources: [{
        src: processedSrc.value,
        type: sourceType.value
      }],
      techOrder: ['html5'],
      html5: {
        hls: {
          enableLowInitialPlaylist: true,
          smoothQualityChange: true,
          overrideNative: true,
          handleManifestRedirects: true
        }
      },
      preload: 'auto'
    }

    console.log('🎬 播放器配置:', options)

    // 创建播放器实例
    player.value = videojs(videoPlayer.value, options, function() {
      console.log('✅ Video.js播放器已就绪')
      playerStatus.value = '播放器就绪'
      emit('ready', this)
      
      // 监听播放事件
      this.on('loadeddata', () => {
        console.log('📹 视频数据已加载')
        hasVideoData.value = true
        showStatus.value = false
        emit('loaded')
      })
      
      this.on('error', (error) => {
        console.error('❌ 播放器错误:', error)
        handleVideoError(error)
      })
    })

  } catch (error) {
    console.error('❌ 初始化失败:', error)
    handleVideoError(error)
  }
}

// 错误处理
const handleVideoError = (error) => {
  console.error('视频播放错误详情:', error)
  
  let message = '视频加载失败'
  
  if (isRTSP.value) {
    message = 'RTSP流需要后端转码服务支持'
  } else if (error?.code === 4) {
    message = '视频源不可用，请检查网络连接'
  } else if (error?.code === 2) {
    message = '视频格式不支持'
  } else if (error?.message?.includes('Network')) {
    message = '网络错误，无法加载视频'
  } else if (error?.message?.includes('format')) {
    message = '视频格式不受支持'
  }
  
  errorMessage.value = message
  playerStatus.value = '错误: ' + message
  emit('error', { error, message, src: processedSrc.value })
}

// 事件处理器
const onVideoLoaded = () => {
  console.log('📹 视频数据已加载')
  hasVideoData.value = true
  showStatus.value = false
}

const onVideoError = (e) => {
  console.error('📹 原生视频错误:', e)
  handleVideoError(e)
}

const onLoadStart = () => {
  console.log('🔄 开始加载视频...')
  playerStatus.value = '加载中...'
}

const onStalled = () => {
  console.log('⚠️ 视频加载被阻塞')
  playerStatus.value = '加载被阻塞'
}

const onWaiting = () => {
  console.log('⏳ 等待缓冲...')
  playerStatus.value = '缓冲中...'
}

// 控制方法
const retry = () => {
  console.log('🔄 重试加载视频')
  errorMessage.value = ''
  hasVideoData.value = false
  showStatus.value = true
  
  if (player.value) {
    player.value.src({
      src: processedSrc.value,
      type: sourceType.value
    })
    player.value.load()
  } else {
    initPlayer()
  }
}

const testVideo = () => {
  console.log('🧪 测试视频播放')
  const testSrc = 'https://www.w3schools.com/html/mov_bbb.mp4'
  if (player.value) {
    player.value.src({
      src: testSrc,
      type: 'video/mp4'
    })
  }
}

const toggleDebug = () => {
  emit('debug', { debug: !props.debug })
}

// 生命周期
onMounted(() => {
  console.log('🚀 VideoPlayerDebug组件挂载')
  nextTick(() => {
    initPlayer()
  })
})

onUnmounted(() => {
  if (player.value) {
    player.value.dispose()
    player.value = null
    console.log('🗑️ 播放器已销毁')
  }
})

// 监听src变化
watch(() => props.src, (newSrc, oldSrc) => {
  if (newSrc !== oldSrc) {
    console.log('📝 视频源已更改:', newSrc)
    retry()
  }
})

// 暴露方法
defineExpose({
  retry,
  testVideo,
  getPlayer: () => player.value
})
</script>

<style scoped>
.video-debug-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: #000;
}

.debug-panel {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 15px;
  border-radius: 8px;
  font-size: 12px;
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

.debug-panel p {
  margin: 2px 0;
}

.video-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.status-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.status-content {
  text-align: center;
  color: white;
  padding: 20px;
}

.loading-status .loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #fff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 10px;
}

.error-status {
  color: #ff6b6b;
}

.error-icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.retry-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

.retry-btn:hover {
  background: #0056b3;
}

.small-text {
  font-size: 12px;
  opacity: 0.8;
}

.controls {
  position: absolute;
  bottom: 10px;
  right: 10px;
  z-index: 100;
}

.controls button {
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  padding: 5px 10px;
  margin: 2px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.controls button:hover {
  background: rgba(0, 0, 0, 0.8);
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

:deep(.video-js) {
  width: 100%;
  height: 100%;
}

:deep(.vjs-tech) {
  object-fit: cover;
}
</style>